import json

from odoo import http
from odoo.addons.basic_configuration.decorate.controller_exception_handler import exception_handler, PayException
from odoo.addons.rp_customer_management.functions.customer_functions import CustomerFunctions
from odoo.addons.rp_shipment_management.functions.ship_order_fc import ShipOrderFC
from odoo.http import request
from werkzeug.utils import redirect
from odoo.addons.basic_configuration.config.env_config import switch_env


class OrderPayController(http.Controller):

    @http.route('/order/check/success', type='http', auth='public', method=['GET'])
    def success_callback(self, cookie, way, payment_code):
        """
        Odoo后台中回调【二维码支付成功回调，Odoo后台支付成功回调】
        Params:
        -order_id:订单ID
        -cookie:登录信息
        -way:支付方式
        """
        # NOTE Stripe支付成功之后进行余额扣减
        rp_payment_id = request.env['rp.payment'].sudo().search([('code', '=', payment_code.strip())])
        balance_price = rp_payment_id.total_balance_price
        # 回溯前置单据
        advanced_model = rp_payment_id.advance_document_id.field_name_id.model
        advanced_model_id = rp_payment_id.advance_document_id.field_record_id
        advanced_model_record_id = request.env[advanced_model].sudo().search([('id', '=', advanced_model_id)])
        if balance_price != 0.0:
            # 余额扣减
            customer_id = advanced_model_record_id.customer_id
            CustomerFunctions(request.env).pay_out(customer_id.rp_customer_balance_id, balance_price)
        # 更新订单数据
        ShipOrderFC(request.env).action_to_pay(advanced_model_record_id, payment_code)
        # 页面跳转
        if way == 'qr_code':
            # qr_code采用的是一个固定的线上IP
            url = '{}/?successfully_order_id={}'.format(switch_env['h5_url']['url'], advanced_model_record_id.id)
            response = redirect(url)
            return response
        elif way == 'odoo':
            url = '{}:{}/web#id={}&cids=1&model=rp.ship.order&view_type=form'.format(switch_env.get('env').get('ip'), switch_env.get('env').get('port'), advanced_model_record_id.id)
            response = redirect(url)
            response.headers['Cookie'] = cookie
            return response

    @http.route('/order/check/fail', type='http', auth='public', method=['GET'])
    @exception_handler
    def fail_callback(self, cookie, way, payment_code):
        """
        取消支付回调
        """
        rp_payment_id = request.env['rp.payment'].sudo().search([('code', '=', payment_code.strip())])
        advanced_model = rp_payment_id.advance_document_id.field_name_id.model
        advanced_model_id = rp_payment_id.advance_document_id.field_record_id
        advanced_model_record_id = request.env[advanced_model].sudo().search([('id', '=', advanced_model_id)])
        # 更新状态，取消支付
        advanced_model_record_id._depends_step_five()
        advanced_model_record_id._depends_step_six()
        if way == 'odoo':
            url = '{}:{}/web#id={}&cids=1&model=rp.ship.order&view_type=form'.format(switch_env.get('env').get('ip'), switch_env.get('env').get('port'), advanced_model_record_id.id)
            response = redirect(url)
            response.headers['Cookie'] = cookie
        else:
            raise PayException('用户取消支付！')
        # 跳转页面
        return response
